# 超极简HTTP服务器 - 专为Windows环境设计
# 使用Python标准库，无需任何外部依赖

import http.server
import socketserver
import time
import sys
import os
import random
import hashlib
import json
import secrets

# 确保中文正常显示
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')

# 设置工作目录为脚本所在目录
os.chdir(os.path.dirname(os.path.abspath(__file__)))

# 简单的JWT token生成器
class TokenGenerator:
    def __init__(self):
        self.secret_key = "homework_ai_system_secret_key_2024"
        
    def generate_token(self, user_id, username):
        """生成标准JWT格式的token"""
        # JWT Header
        header = {
            'alg': 'HS256',
            'typ': 'JWT'
        }
        
        # 构造token payload
        payload = {
            'user_id': user_id,
            'username': username,
            'iat': int(time.time()),  # issued at
            'exp': int(time.time()) + (24 * 60 * 60)  # 过期时间：24小时后
        }
        
        # 按照标准JWT格式: base64url(header).base64url(payload).base64url(signature)
        import base64
        
        # Base64URL编码函数
        def base64url_encode(data):
            # 标准base64编码
            encoded = base64.b64encode(data.encode('utf-8')).decode('utf-8')
            # 转换为base64url格式（JWT标准）
            return encoded.replace('+', '-').replace('/', '_').rstrip('=')
        
        # 编码header和payload
        header_b64 = base64url_encode(json.dumps(header, separators=(',', ':')))
        payload_b64 = base64url_encode(json.dumps(payload, separators=(',', ':')))
        
        # 生成签名
        signing_input = f"{header_b64}.{payload_b64}"
        signature = hashlib.sha256(
            f"{signing_input}{self.secret_key}".encode('utf-8')
        ).hexdigest()
        
        # 返回标准JWT格式: header.payload.signature
        return f"{header_b64}.{payload_b64}.{signature}"
    
    def verify_token(self, token):
        """验证标准JWT格式的token"""
        try:
            parts = token.split('.')
            if len(parts) != 3:
                return False, "无效的token格式，期望3个部分"
            
            header_b64, payload_b64, signature_b64 = parts
            
            # Base64URL解码函数
            def base64url_decode(data):
                # 转换为标准base64格式
                padded = data + '=' * (4 - len(data) % 4)
                # 转换回标准字符
                base64_standard = padded.replace('-', '+').replace('_', '/')
                import base64
                return base64.b64decode(base64_standard.encode('utf-8')).decode('utf-8')
            
            # 验证签名
            signing_input = f"{header_b64}.{payload_b64}"
            expected_signature = hashlib.sha256(
                f"{signing_input}{self.secret_key}".encode('utf-8')
            ).hexdigest()
            
            if signature_b64 != expected_signature:
                return False, "Token签名无效"
            
            # 解码payload
            payload_json = base64url_decode(payload_b64)
            payload = json.loads(payload_json)
            
            # 检查过期时间
            if payload['exp'] < int(time.time()):
                return False, "Token已过期"
            
            return True, payload
            
        except Exception as e:
            return False, f"Token验证失败: {str(e)}"

# 全局token生成器
token_generator = TokenGenerator()

# 日志函数
def log(message):
    timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
    print(f'[{timestamp}] {message}')

# 模拟数据库 - 存储用户信息
class MockDatabase:
    def __init__(self):
        self.users = {}
        self.current_id = 1
    
    def add_user(self, username, email, password):
        if username in self.users:
            return None, "用户名已存在"
        if any(user['email'] == email for user in self.users.values()):
            return None, "邮箱已被注册"
        
        user_id = self.current_id
        self.users[username] = {
            'id': user_id,
            'username': username,
            'email': email,
            'password': password  # 注意：实际应用中需要加密存储
        }
        self.current_id += 1
        return user_id, "注册成功"
    
    def verify_user(self, username, password):
        if username not in self.users:
            return None, "用户不存在"
        
        user = self.users[username]
        if user['password'] != password:
            return None, "密码错误"
        
        return user['id'], "登录成功"

# 创建全局数据库实例
database = MockDatabase()

# 简单的请求处理器
class SimpleHandler(http.server.BaseHTTPRequestHandler):
    def _send_cors_headers(self):
        """发送CORS头"""
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With')
        self.send_header('Access-Control-Allow-Credentials', 'true')

    def do_OPTIONS(self):
        """处理预检请求"""
        self.send_response(200)
        self._send_cors_headers()
        self.send_header('Content-Type', 'text/plain; charset=utf-8')
        self.end_headers()
        log(f'OPTIONS {self.path} 200 - CORS预检')

    def do_GET(self):
        # 添加CORS头
        self.send_response(200)
        self._send_cors_headers()
        
        if self.path == '/':
            # 根路径返回欢迎页面
            self.send_header('Content-Type', 'text/html; charset=utf-8')
            self.end_headers()
            
            html = f'''
            <!DOCTYPE html>
            <html>
            <head>
                <title>AI聊天系统</title>
                <meta charset="utf-8">
            </head>
            <body>
                <h1>AI聊天系统后端服务</h1>
                <p>服务运行中！当前时间: {time.strftime('%Y-%m-%d %H:%M:%S')}</p>
                <p>API地址: <code>/api/ai/chat</code> (POST请求)</p>
                <p>注册接口: <code>/api/auth/register</code> (POST请求)</p>
                <p>登录接口: <code>/api/auth/login</code> (POST请求)</p>
                <p>健康检查: <code>/health</code> (GET请求)</p>
            </body>
            </html>
            '''
            
            self.wfile.write(html.encode('utf-8'))
            log(f'GET {self.path} 200')
            
        elif self.path == '/health':
            # 健康检查端点
            self.send_header('Content-Type', 'text/plain; charset=utf-8')
            self.end_headers()
            
            self.wfile.write(f'OK - {time.strftime('%Y-%m-%d %H:%M:%S')}'.encode('utf-8'))
            log(f'GET {self.path} 200')
            
        else:
            # 404响应
            self.send_response(200)
            self._send_cors_headers()
            
            self.wfile.write(f'404 - 页面未找到: {self.path}'.encode('utf-8'))
            log(f'GET {self.path} 404')
    
    def do_POST(self):
        try:
            content_length = int(self.headers.get('Content-Length', 0))
            if content_length > 0:
                post_data = self.rfile.read(content_length).decode('utf-8')
                # 尝试解析JSON数据
                import json
                try:
                    data = json.loads(post_data)
                except json.JSONDecodeError:
                    data = {}
            else:
                data = {}
        except Exception as e:
            data = {}
            log(f'解析请求数据时出错: {str(e)}')
        
        if self.path == '/api/auth/register':
            # 用户注册接口
            self.send_response(200)
            self._send_cors_headers()
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            
            username = data.get('username', '')
            email = data.get('email', '')
            password = data.get('password', '')
            
            log(f'收到注册请求: username={username}, email={email}')
            
            # 简单验证
            if not username or not email or not password:
                self.end_headers()
                response = json.dumps({
                    'success': False,
                    'message': '用户名、邮箱和密码不能为空'
                }, ensure_ascii=False)
                self.wfile.write(response.encode('utf-8'))
                log(f'POST {self.path} 400 - 缺少必要参数')
                return
            
            # 注册用户
            user_id, message = database.add_user(username, email, password)
            
            if user_id:
                # 生成JWT格式的token
                token = token_generator.generate_token(user_id, username)
                
                self.end_headers()
                response = json.dumps({
                    'success': True,
                    'message': message,
                    'data': {
                        'id': user_id,
                        'username': username,
                        'email': email,
                        'token': token
                    }
                }, ensure_ascii=False)
                self.wfile.write(response.encode('utf-8'))
                log(f'POST {self.path} 200 - 用户注册成功')
            else:
                self.end_headers()
                response = json.dumps({
                    'success': False,
                    'message': message
                }, ensure_ascii=False)
                self.wfile.write(response.encode('utf-8'))
                log(f'POST {self.path} 400 - {message}')
                
        elif self.path == '/api/auth/login':
            # 用户登录接口
            username = data.get('username', '')
            password = data.get('password', '')
            
            log(f'收到登录请求: username={username}')
            
            # 简单验证
            if not username or not password:
                self.send_response(400)
                self._send_cors_headers()
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.end_headers()
                response = json.dumps({
                    'success': False,
                    'message': '用户名和密码不能为空'
                }, ensure_ascii=False)
                self.wfile.write(response.encode('utf-8'))
                log(f'POST {self.path} 400 - 缺少必要参数')
                return
            
            # 验证用户
            user_id, message = database.verify_user(username, password)
            
            if user_id:
                # 查找用户信息
                user = None
                for u in database.users.values():
                    if u['id'] == user_id:
                        user = u
                        break
                
                # 生成JWT格式的token
                token = token_generator.generate_token(user_id, user['username'])
                
                self.send_response(200)
                self._send_cors_headers()
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.end_headers()
                response = json.dumps({
                    'success': True,
                    'message': message,
                    'data': {
                        'id': user_id,
                        'username': user['username'],
                        'email': user['email'],
                        'token': token
                    }
                }, ensure_ascii=False)
                self.wfile.write(response.encode('utf-8'))
                log(f'POST {self.path} 200 - 用户登录成功')
            else:
                self.send_response(401)
                self._send_cors_headers()
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.end_headers()
                response = json.dumps({
                    'success': False,
                    'message': message
                }, ensure_ascii=False)
                self.wfile.write(response.encode('utf-8'))
                log(f'POST {self.path} 401 - {message}')
                
        elif self.path == '/api/ai/chat':
            # 模拟AI聊天接口
            self.send_response(200)
            self._send_cors_headers()
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.end_headers()
            
            try:
                log(f'收到AI聊天请求: {post_data[:100]}...')
                
                # 返回模拟响应
                response = json.dumps({
                    'success': True,
                    'data': {
                        'response': f'我已收到你的消息，时间: {time.strftime("%Y-%m-%d %H:%M:%S")}'
                    }
                }, ensure_ascii=False)
                self.wfile.write(response.encode('utf-8'))
                log(f'POST {self.path} 200')
                
            except Exception as e:
                self.send_response(500)
                self._send_cors_headers()
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.end_headers()
                
                response = json.dumps({
                    'success': False,
                    'message': f'错误: {str(e)}'
                }, ensure_ascii=False)
                self.wfile.write(response.encode('utf-8'))
                log(f'POST {self.path} 500 - {str(e)}')
                
        else:
            self.send_response(404)
            self._send_cors_headers()
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.end_headers()
            
            response = json.dumps({
                'success': False,
                'message': f'API未找到: {self.path}'
            }, ensure_ascii=False)
            self.wfile.write(response.encode('utf-8'))
            log(f'POST {self.path} 404')
    
    # 禁用默认日志
    def log_message(self, format, *args):
        return

# 尝试在随机端口上启动服务器
def start_server():
    log('====== 超极简HTTP服务器启动 ======')
    
    # 尝试多个端口
    ports_to_try = [random.randint(10000, 65535) for _ in range(5)]
    
    for port in ports_to_try:
        try:
            log(f'尝试在端口 {port} 上启动...')
            
            # 创建简单的服务器
            with socketserver.TCPServer(('', port), SimpleHandler) as httpd:
                log(f'✅ 服务器启动成功！')
                log(f'访问地址: http://localhost:{port}')
                log(f'API地址: http://localhost:{port}/api/ai/chat')
                log(f'健康检查: http://localhost:{port}/health')
                log(f'按 Ctrl+C 停止服务')
                
                # 运行服务器
                httpd.serve_forever()
                
        except OSError as e:
            log(f'❌ 端口 {port} 被占用: {str(e)}')
            continue
    
    log('❌ 所有端口都被占用，无法启动服务器')
    return False

# 主函数
if __name__ == '__main__':
    try:
        start_server()
    except KeyboardInterrupt:
        log('\n⏸️  服务器已停止')
    except Exception as e:
        log(f'\n❌ 服务器异常: {str(e)}')
    finally:
        log('====== 服务器已退出 ======')